package nancal.mp.service

import nancal.mp.db.mongo.JenkinsLanguageEnum
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nbcp.base.extend.HasValue
import nbcp.base.utils.ResourceUtil


fun JenkinsLanguageEnum.getK8sServiceYamlContent(targetEnv: String): String {
    var setting = mor.dev.appDeploySetting.getAppDeploySetting(targetEnv)

    var languageVersionSetting = setting.getLanguageSetting(this)
    if (languageVersionSetting != null && languageVersionSetting.serviceYaml.HasValue) {
        return languageVersionSetting.serviceYaml
    }

    var fileNameTemplate = "/devops/${
        this.toString().lowercase()
    }/k8s-service.yaml"


    if (ResourceUtil.existsResource(fileNameTemplate)) {
        return ResourceUtil.readResourceContentText(fileNameTemplate)
    }

    return "";
}


fun JenkinsLanguageEnum.getDockerfileContent(targetEnv: String): String {
    var setting = mor.dev.appDeploySetting.getAppDeploySetting(targetEnv)

    var languageVersionSetting = setting.getLanguageSetting(this)
    if (languageVersionSetting != null && languageVersionSetting.dockerfile.HasValue) {
        return languageVersionSetting.dockerfile
    }

    var lang = this.toString().lowercase();

    var fileNameTemplate = "/devops/${
        lang
    }/${lang}.dockerfile"

    if (ResourceUtil.existsResource(fileNameTemplate)) {
        return ResourceUtil.readResourceContentText(fileNameTemplate)
    }

    return "";
}

fun JenkinsLanguageEnum.getK8sDeploymentYamlContent(languageVersion: String, targetEnv: String): String {
    var setting = mor.dev.appDeploySetting.getAppDeploySetting(targetEnv)

    var languageVersionSetting = setting.getLanguageVersionSetting(this, languageVersion)
    if (languageVersionSetting != null && languageVersionSetting.deploymentYaml.HasValue) {
        return languageVersionSetting.deploymentYaml
    }

    var lang = this.toString().lowercase();

    var fileNameTemplate = "/devops/${
        lang
    }/k8s-deployment-${languageVersion}.yaml"

    if (ResourceUtil.existsResource(fileNameTemplate)) {
        return ResourceUtil.readResourceContentText(fileNameTemplate)
    }

    var langSetting = setting.getLanguageSetting(this);
    if (langSetting != null && langSetting.deploymentYaml.HasValue) {
        return langSetting.deploymentYaml
    }

    fileNameTemplate = "/devops/${
        lang
    }/k8s-deployment.yaml"

    if (ResourceUtil.existsResource(fileNameTemplate)) {
        return ResourceUtil.readResourceContentText(fileNameTemplate)
    }


    return "";
}

